/*
 * Copyright (c) Zhongkehonglue Technologies Co., Ltd. 2025. All rights reserved.
 * Description: Implementation of functions related to the periodic task.
 * Author: wangchunyang
 * Create: 2025-05-23
 */
#include "dmcPeriodicTask.h"

#include "dmcDevice.h"
#include "dmcLog.h"

#ifdef LOG_TAG
#undef LOG_TAG
#endif
namespace DlnaDmc {
constexpr dmc_int32 threadSleepTime = 5;
constexpr dmc_int32 periodicSearchDeviceMod = 3;
void PeriodicTask::start() {
    workerThread = std::thread([this]() {
        std::unique_lock<std::mutex> lock(mtx);
        
        while (true) {
            auto status = cv.wait_for(lock, std::chrono::seconds(threadSleepTime), 
                [this] { return shouldStop; });
            if (status && shouldStop) {
                break;
            }
            threadLoopCnt++;
            if (threadLoopCnt % periodicSearchDeviceMod == 0) {
                PeriodicSearchDevice();
            }
            DmcDevice::GetInstance().RemoveOfflineDevice();
        }
    });
}

void PeriodicTask::stop() {
    {
        std::lock_guard<std::mutex> lock(mtx);
        shouldStop = true;
    }
    cv.notify_one();
    
    if (workerThread.joinable()) {
        workerThread.join();
    }
    LOGI("Periodic task thread exists");
}

PeriodicTask::~PeriodicTask() {
    stop();
}
}





